// pages/order/list.js
import Router from '../../utils/router.js';
import util from '../../utils/util.js';
import base from '../../config/base.js';
import orderlistService from '../../services/orderlist.js';
import orderdetailsService from '../../services/orderinfo.js';
import confirmorderService from '../../services/confirmorder.js';
var sta = null,
  orid = null,
  index = null;
Page({

  /*
   * 页面的初始数据
   */
  data: {
    address: wx.getStorageSync('address') || null,
    user_info: wx.getStorageSync('user_info'),
    rootdata: {
      noorder: base.static + '/orders/wudingdan2.png',
      dianpuimg: base.static + '/orders/dianpuimg.png',
      dianpuzuoj: base.static + '/orders/dianpuzuoj.png',
      icon_titlearrow: base.static + 'aftersale/titlearrow.png',
      icon_shopimg: base.static + 'aftersale/shopimg.png',
      icon_afterbackmuch: base.static + 'aftersale/tuimuch.png',
      icon_redthtk: base.static + 'aftersale/redthtk.png',
    },
    navtop: false,
    //按钮频繁拦截
    payflag:false,
    //加载状态
    loadflag: 1,
    orderlength: 1,
    order_list: [],
    limit: 20,
    offset: 1,
    //订单列表 状态
    orderstatus: {
      default: '',
      list: [
        {
          text: '全部',
          status: ''
        },
        {
          text: '待付款',
          status: 3009
        },
        // {
        //   text: '已付款',
        //   status: 3010
        // },
        {
          text: '待发货',
          status: 3010
        },
        {
          text: '待收货',
          status: 3003
        },
        {
          text: '售后',
          status: 3007
        }
      ]
    },
    listflag: false,
    index_num: '',
    onloadNum: 1
  },
  /**
     * 获取该状态下订单
     */
  getorder: function (e) {
    var that = this,
      status = e.currentTarget.dataset.status;
    that.getlist(status);
  },
  /**
   * 根据订单状态获取列表
   */
  getlist: function (status, ty) {
    var that = this,
      orderstatus = that.data.orderstatus;
    if (!!ty) {
      orderstatus.default = status;
      sta = status;
      that.setData({
        orderstatus: orderstatus,
        order_list: [],
        loadflag: 1
      });
      that.queryorderlist();
    } else {
      if (orderstatus.default != status) {
        orderstatus.default = status;
        sta = status;
        that.setData({
          orderstatus: orderstatus,
          order_list: [],
          loadflag: 1,
          orderlength: 1
        });
        that.setData({
          offset: 1
        });
        that.queryorderlist();
      }
    }
  },
  /**
   * 获取订单列表
   */
  queryorderlist: function () {
    var that = this,
      loadflag = that.data.loadflag,
      offset = that.data.offset,
      limit = that.data.limit,
      status = that.data.orderstatus.default,
      param = {},
      serviceController = 'queryorderlist';
    if (status == 3007) {
      serviceController = 'querysaleorderlist';
    } else {
      if (status) {
        param.order_status = status;
      }
    }
    param.limit = limit;
    param.offset = offset;
    orderlistService[serviceController](param, (res) => {
      // 成功
      if (res && res.code == 1) {
        let order_list = res.data;
        /**
         *3002  等待发货
          3003  已发货
          3004  成功的订单
          3005  待结算
          3006  已结算
          3007  售后中
          3008  已退款
          3013  交易关闭
         */
        for (let index in order_list) {
          let order_status = order_list[index].order_status,
            str_attr_val_name_obj = order_list[index].str_attr_val_name,
            str_attr_val_name = '';
          for (let k in str_attr_val_name_obj){
            str_attr_val_name += k + '：' + str_attr_val_name_obj[k] + '   ';
          }
          order_list[index].str_attr_val_name = str_attr_val_name;

          if (order_list[index].real_money != null && order_list[index].real_money != '' && !isNaN(Number(order_list[index].real_money))) {
            order_list[index].real_money = util.toDecimal2(util.floatAccMul(order_list[index].real_money, 1));
          }
          if (order_list[index].orig_price != null && order_list[index].orig_price != '' && !isNaN(Number(order_list[index].orig_price))) {
            order_list[index].orig_price = util.toDecimal2(util.floatAccMul(order_list[index].orig_price, 1));
          }
          if (order_list[index].total_money != null && order_list[index].total_money != '' && !isNaN(Number(order_list[index].total_money))) {
            // order_list[index].total_money = util.toDecimal2(util.floatAccMul(order_list[index].total_money, order_list[index].goods_num));
          }else{
            // order_list[index].total_money = order_list[index].real_money * order_list[index].goods_num;
          }
          if (order_list[index].commission != null && order_list[index].commission != '' && !isNaN(Number(order_list[index].commission))) {
            order_list[index].commission = util.toDecimal2(util.floatAccMul(order_list[index].commission, 1));
          }
          order_list[index].order_status_txt = that.getorderstatustxt(order_status);
          if (order_list[index].goods_img != null && order_list[index].goods_img != '' && order_list[index].goods_img.indexOf('http://') == -1 && order_list[index].goods_img.indexOf('https://') == -1){
            order_list[index].goods_img = 'http://' + order_list[index].goods_img + '?x-oss-process=image/resize,h_320';
          }
        }
        order_list = that.data.order_list.concat(order_list);
        if (res.data.length < limit) {
          loadflag = 0;
        } else {
          loadflag = 1;
        }
        let orderlength = order_list.length;
        if (orderlength <= 2){
          loadflag = 'hide';
        }
        that.setData({
          loadflag, order_list, orderlength
        });
      } else {
        loadflag = 0;
        let orderlength = that.data.order_list.length;
        // wx.showToast({
        //   title: res.msg,
        //   icon: 'none'
        // })
        that.setData({
          loadflag, orderlength
        });
      }
    }, (res) => {
      that.setData({
        listflag: true
      });
      loadflag = -1;
      wx.stopPullDownRefresh();
      if (res && res.statusCode != 200) {
        if (offset > 1) {
          offset--;
        } else {
          offset = 1;
        }
        that.setData({
          loadflag, offset
        });
      }
    });

  },
  getorderstatustxt: function (order_status){
    var order_status_txt = '';
    if (order_status == '3002') {
      order_status_txt = '待发货';
    } else if (order_status == '3003') {
      order_status_txt = '待收货';
    } else if (order_status == '3004') {
      order_status_txt = '已签收';
    } else if (order_status == '3005') {
      order_status_txt = '已签收';
    } else if (order_status == '3006') {
      order_status_txt = '已签收';
    } else if (order_status == '3007') {
      order_status_txt = '售后中';
    } else if (order_status == '3008') {
      order_status_txt = '已退款';
    } else if (order_status == '3009') {
      order_status_txt = '待付款';
    } else if (order_status == '3010') {
      order_status_txt = '待发货';
    } else if (order_status == '3011') {
      order_status_txt = '已取消';
    } else if (order_status == '3013') {
      order_status_txt = '交易关闭';
    }
    return order_status_txt;
  },
  /**
   * 支付失败调用
   */
  payfail:function(){
    wx.showToast({
      title: '支付无效',
      icon: 'none'
    })
  },
  /**
   * 立即付款
   */
  gopayment:function(e){
    let that = this,
      index = e.currentTarget.dataset.index,
      item = that.data.order_list[e.currentTarget.dataset.index],
      user_info = that.data.user_info,
      payflag = true,
      datas = {};
    if (that.data.payflag) {
      return false;
    }
    that.setData({
      payflag: payflag,
      index_num:index,
    });
    if (item.run_num == null || item.run_num == '') {
      that.payfail();
      return;
    }
    datas.run_num = item.run_num;
    datas.orid = item.orid;
    if (user_info.openid == null || user_info.openid == '') {
      that.payfail();
      return;
    }
    datas.openid = user_info.openid;
    if (user_info.user_nickname == null || user_info.user_nickname == '') {
      that.payfail();
      return;
    }
    datas.bsln_name = user_info.user_nickname;
    that.toPay(datas, index);
  },
  // 支付
  toPay: function (data, index) {
    let that = this;
    let opt = {
      run_num: data.run_num,
      orid: data.orid,
      // store_id: store_id,
      // total_money: data.total_money,
      openid: data.openid,
      bsln_name: data.user_nickname,
    }

    confirmorderService.payOrder(opt, res => {
      if (res && res.code == 1) {
        let d = res.data;
        util.toPay(d, b => {
          if (b) {
            // 成功
            wx.showToast({
              title: '支付成功,加载中...',
              icon: 'none',
              complete: function () {
                setTimeout(() => {
                  let order_list = that.data.order_list;
                  order_list[index].order_status = 3010;
                  order_list[index].order_status_txt = '待发货';
                  that.setData({
                    order_list
                  })
                  let scene = '',
                    activity = wx.getStorageSync('activity');
                  if (activity && activity.payorder_get_redpacket==1 ){
                    scene = 'singlePage';
                  }
                  // that.goorderdetails({
                  //   currentTarget: {
                  //     dataset: {
                  //       index: index
                  //     }
                  //   }
                  // }, scene)
                },1500);
              }
            });
            //let orid = b.data.orid;
            //let run_num = b.data.run_num;
            Router.go('payhot', `orid=${data.orid}&run_num=${data.run_num}&store`);
          } else {
            // 失败
            
          }
          let payflag = false;
          that.setData({
            payflag
          });
        })
      } else {
        let payflag = false;
        that.setData({
          payflag
        });
        return wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 5000
        });
      }
    }, res =>{
      if (res && res.statusCode != 200) {
        let payflag = false;
        that.setData({
          payflag
        });
      }
    });

  },
  /**
   * 取消订单
   */
  cancelorder: function (e) {
    let that = this,
      index = e.currentTarget.dataset.index;
    wx.showModal({
      content: '确定取消订单吗？',
      success: function (res) {
        if(res.confirm){
          that.updatestatuswaitcancel(index);
        }
      }
    })
  },
  /**
   * 获取订单详情
   */
  queryorderdetails: function (index, orid) {
    let that = this,
      param = {};
    if (!orid) {
      wx.showToast({
        title: '暂无订单',
        icon: 'none',
        complete: function () {
          wx.navigateBack();
        }
      })
      return;
    }
    param.orid = orid;
    orderdetailsService.queryorderdetails(param, res => {
      // 成功
      if (res && res.code == 1) {
        let info = res.data,
          order_list = that.data.order_list;
        if (info.order_status != order_list[index].order_status && that.data.orderstatus.default != '' && that.data.orderstatus.default != undefined) {
          order_list.splice(index, 1);
        } else {
          order_list[index].order_status = info.order_status;
          order_list[index].order_status_txt = that.getorderstatustxt(info.order_status);
        }
        let orderlength = order_list.length,
          loadflag = that.data.loadflag;
        if (orderlength <= 2) {
          loadflag = 'hide';
        } else if (orderlength <= 0) {
          loadflag = 0;
        }
        that.setData({
          order_list, loadflag, orderlength
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    });

  },
  /**
   * 待付款 变成 已取消
   */
  updatestatuswaitcancel: function (index) {
    let that = this,
      order_list = that.data.order_list,
      orid = order_list[index].orid,
      update_status = 3004,
      update_status_str = '',
      param = {};
    if (order_list[index].order_status == 3009){
      update_status_str = 'wait_cancel';
    } else if (order_list[index].order_status == 3010) {
      update_status_str = 'success_cancel';
    } else if (order_list[index].order_status == 3003){
      update_status_str = 'have_send_have_get';      
    }
    if (!orid) {
      wx.showToast({
        title: '订单异常',
        icon: 'none'
      })
      return;
    }
    param.orid = orid;
    param.update_status = update_status_str;
    orderdetailsService.updatestatuswaitcancel(param, res => {
      if (res && res.code == 1) {
        wx.showModal({
          content: '确认收货成功!\r\n快去发表评价吧！',
          cancelText: '取消',
          confirmText: '去评价',
          confirmColor: '#FE3F3E',
          success(res) {
            if (res.confirm){
              Router.go('evaluate', `orid=${orid}&page=list`);              
            }
          }
        })
        //重新获取订单信息
        order_list[index].order_status = update_status;
        order_list[index].order_status_txt = that.getorderstatustxt(update_status);
        that.setData({
          order_list
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  /**
   * 查看物流详情
   */
  gologistics: function (e) {
    let that = this,
      item = that.data.order_list[e.currentTarget.dataset.index],
      courier_number = item.courier_number,
      express_company = item.express_company,
      goods_img = item.goods_img;
    orid = item.orid;
    index = e.currentTarget.dataset.index;
    if (express_company === '' || express_company == null) {
      express_company = '其他';
    }
    if (item.srlnid){
      Router.go('logistics', `courier_number=${courier_number}&express_company=${express_company}&goods_img=${goods_img}&srlnid=${item.srlnid}&run_num=${item.run_num}`);      
    }else {
      Router.go('logistics', `courier_number=${courier_number}&express_company=${express_company}&goods_img=${goods_img}`);      
    }
  },
  /**
   * 查看订单详情页
   */
  goorderdetails: function (e, scene) {
    let that = this,
      item = that.data.order_list[e.currentTarget.dataset.index],
      str = `orid=${item.orid}`;
      orid = item.orid;
    if (scene && scene =='singlePage'){
      str += `&scene=singlePage`
    }
    let index = e.currentTarget.dataset.index;
    if (e.currentTarget.dataset.saleaftertype){
      str = `srorid=${item.srorid}&orid=${item.orid}`;
      Router.go('afterdetail', str);
    }else{
      Router.go('orderDetail', str);
    }
    
  },
  /**
   * 查看店铺详情
   */
  gostore:function(e){
    let that = this,
      item = that.data.order_list[e.currentTarget.dataset.index],
      store_id = item.bslnid;
    index = e.currentTarget.dataset.index;
    Router.go('store', `store_id=${store_id}`, `reLaunch`);
  },
  
  //去售后类型页面
  goservicetype(e) {
    let index = e.currentTarget.dataset.index;
    let order_list = this.data.order_list[index];
    let orid = order_list.orid;
    Router.go('servicetype', `orid=${orid}`);
  },
  //去评级页面
  goevaluate(e){
    let index = e.currentTarget.dataset.index;
    let order_list = this.data.order_list[index];
    let orid = order_list.orid;
    Router.go('evaluate', `orid=${orid}&page=list`);
  }, 
   //点击确认收货
  goConfirmationReceipt(e){
    console.log(e)
    let that = this;
     let index = e.currentTarget.dataset.index;
     wx.showModal({
       content: '是否确认已收货？',
       cancelText: '取消',
       confirmText: '确认',
       confirmColor: '#FE3F3E',
       success(res){
         if (res.confirm){
           that.updatestatuswaitcancel(index)
          
         }
       }
     })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.method && options.method == 'navigateBack') {
    } else {
      sta = options.status;
      console.log(sta)
      let that = this,
        orderstatus = that.data.orderstatus;
      orderstatus.default = sta;
      that.setData({
        user_info: wx.getStorageSync('user_info'),
        orderstatus,
      });
      that.queryorderlist();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    if (orid != null && orid !== '' && index !== null && index !== '') {
      //that.queryorderdetails(index, orid);
    }
    if(that.data.onloadNum != 1){
      that.setData({
        order_list: []
      })
      that.queryorderlist();
    }
    that.setData({
      onloadNum: 2
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    orid = null;
    index = null;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    that.setData({
      order_list: [],
      loadflag: 1,
      offset: 1,
      orderlength:1
    });
    if (sta == undefined) {
      that.queryorderlist();
    } else {
      that.getlist(sta, 1);
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this,
      loadflag = that.data.loadflag,
      listflag = that.data.listflag;
    if (!listflag){
      return ;
    }
    that.setData({
      listflag: false
    });
    if (loadflag == 1) {
      let offset = that.data.offset;
      offset++;
      that.setData({
        offset
      });
      that.queryorderlist();
    }
  },
  /**
  * 
  */
  onPageScroll: function (e) {
    var top = e.scrollTop,
      scrolltop = top,
      navtop = this.data.navtop,
      distance = 21;
    if (top > distance  && !navtop){
      navtop = true;
      this.setData({
        navtop, scrolltop
      })
    }
    if (top <= distance && navtop){
      navtop = false;
      this.setData({
        navtop, scrolltop
      })
    }
    if (top == 0) {
      this.setData({
        scrolltop
      })
    }
    
  },
  goscoltop: function () {
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
})